//
//  CMVerCodeCtrl.m
//  CreditManger
//
//  Created by 于会海 on 15/11/2.
//  Copyright © 2015年 jinxin. All rights reserved.
//

#import "CMVerCodeCtrl.h"
#import "CMBankLoginCtrl.h"
#import "CMGetRegMobileCodeParam.h"
#import "CMGetRegMobileCodeParser.h"
#import "CMGetRegMobileCodeInfo.h"
#import "CMRegistParam.h"
#import "CMRegistParser.h"
#import "CMLoginUserInfo.h"
#import "CMLoginManager.h"
#import "CheckValid.h"
#import "CMBankRegistCtrl.h"

@interface CMVerCodeCtrl ()<UITextFieldDelegate,UIAlertViewDelegate>

@property (weak, nonatomic) IBOutlet UILabel *phoneNumber;
@property (weak, nonatomic) IBOutlet UITextField *verCode;
@property (weak, nonatomic) IBOutlet UIButton *doDownBtn;
@property (weak, nonatomic) IBOutlet UIButton *reCodeBtn;
- (IBAction)reCodeBtnClicked:(UIButton *)sender;
- (IBAction)doDownBtnClicked:(UIButton *)sender;

@end

@implementation CMVerCodeCtrl


- (void)viewDidLoad {
    [super viewDidLoad];
    [[NSUserDefaults standardUserDefaults] setObject:[NSString stringWithFormat:@"%f",[NSDate date].timeIntervalSince1970 + 120] forKey:REGIST_CODE_TIME];
    [[NSUserDefaults standardUserDefaults] synchronize];
    self.doDownBtn.layer.cornerRadius = 4;
}

- (void)buildLayout
{
    self.title = @"短信验证码";
    NSString* str = self.phoneNum;
    NSString* string1 = [str substringToIndex:3];
    NSString* string2 = [str substringWithRange:NSMakeRange(3, 4)];
    NSString* string3 = [str substringWithRange:NSMakeRange(7, 4)];
    NSMutableString* string4  = [[NSMutableString alloc] initWithCapacity:13];
    [string4 appendFormat:@"\"%@ %@ %@\"",string1,string2,string3];
    self.phoneNumber.text = string4;
    
    self.verCode.text = self.phoneVerCode;//上线测试可以注销
    self.verCode.delegate = self;
}

#pragma  textField delegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if ([string isEqualToString:@"\n"]) {
        return YES;
    }
    NSString* toBeString = [textField.text stringByReplacingCharactersInRange:range withString:string];
    if (self.verCode == textField) {
        if ([toBeString length] > 6) {
            return NO;
        }
    }
    return YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)doBack{
    LLog(@"返回");
    if (self.doBackBlock) {
        self.doBackBlock(YES);
    }
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)reCodeBtnClicked:(UIButton *)sender {
    LLog(@"重新获取验证码");
    CMGetRegMobileCodeParam* param = [[CMGetRegMobileCodeParam alloc] init];
    param.mobile = self.phoneNum;
    param.gid = @"";
    CMGetRegMobileCodeParser* parser = [[CMGetRegMobileCodeParser alloc] init];
    [NetCenter postDataFromURL:Method_getRegMobileCode params:param parser:parser result:^(ParserResult *myResult) {
        if (myResult.code == 0) {
            CMGetRegMobileCodeInfo* info = (CMGetRegMobileCodeInfo*)myResult.result;
            self.verCode.text = info.mobileCode;//测试或者上线前注销
        }else{
            DISSMISS_ERR(myResult.message);
        }
    } failure:^(NSError *error) {
        DISSMISS_ERR(error.description);
    }];
    
    [[NSUserDefaults standardUserDefaults] setObject:[NSString stringWithFormat:@"%f",[NSDate date].timeIntervalSince1970 + 120] forKey:REGIST_CODE_TIME];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

- (IBAction)doDownBtnClicked:(UIButton *)sender {
    LLog(@"确定按钮");
    if([CheckValid checkStrIsEmpty:self.verCode.text]){
        [self.verCode becomeFirstResponder];
        DISSMISS_ERRView(@"验证码不能为空",[[[UIApplication sharedApplication] windows] lastObject]);
        return;
    }else{
        [self.verCode resignFirstResponder];
        [self requestToLoginBankVC];
    }
}

- (void)requestToLoginBankVC
{
    CMRegistParam* param = [[CMRegistParam alloc] init];
    param.mobile = self.phoneNum;
    param.password = self.password;
    param.mobileCode = self.verCode.text;
    param.os = DefaultSystemVersion;
    param.gid = [self getGID];
    param.osVersion = DefaultAppVersion;
    param.channel = @"";
    param.factory = @"";
    param.model = @"";
    param.appVersion = @"";
    param.resolution = @"";
    /*
     #if defined (MACROSTORE)
     param.appType = @"1";
     #else
     param.appType = @"0";
     #endif
     */
    CMRegistParser* parser = [[CMRegistParser alloc] init];
    [NetCenter postDataFromURL:Method_regist params:param parser:parser result:^(ParserResult *myResult) {
        if (myResult.code == 0) {
            dispatch_time_t when = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC));
            dispatch_after(when, dispatch_get_main_queue(), ^{
                
                CMLoginUserInfo *info = (CMLoginUserInfo *)myResult.result;
                [CMLoginManager cacheCurrentUserToUserDefault:info];
                
                CMBankRegistCtrl* bankRegistVC = [[CMBankRegistCtrl alloc] init];
                CMNavigationController *nav = [[CMNavigationController alloc]initWithRootViewController:bankRegistVC];
                [UIApplication sharedApplication].keyWindow.rootViewController = nav;
                
            });
            
        }else if (myResult.code == 1){
            DISSMISS_ERR(myResult.message);
        }
    } failure:^(NSError *error) {
        DISSMISS_ERR(error.description);
    }];
}

- (NSString*)getGID
{
    NSUUID *identifierForVendor = [[UIDevice currentDevice] identifierForVendor];
    NSString *deviceId = [identifierForVendor UUIDString];
    return deviceId;
}

- (void)makeTime{
    dispatch_async(dispatch_get_main_queue(), ^{
        NSTimeInterval timeLast = [[[NSUserDefaults standardUserDefaults] objectForKey:REGIST_CODE_TIME] longLongValue];
        if (timeLast <= 0){
            self.reCodeBtn.enabled = YES;
            [self.reCodeBtn setTitle:@"" forState:UIControlStateNormal];
            [self.reCodeBtn setTitle:@"" forState:UIControlStateDisabled];
            return;
        }
        NSTimeInterval now = [NSDate date].timeIntervalSince1970;
        if (now >= timeLast){
            self.reCodeBtn.enabled = YES;
            [self.reCodeBtn setTitle:@"" forState:UIControlStateNormal];
            [self.reCodeBtn setTitle:@"" forState:UIControlStateDisabled];
            self.reCodeBtn.backgroundColor = [UIColor clearColor];
            return;
        }
        self.reCodeBtn.enabled = NO;
        [self.reCodeBtn setTitle:[NSString stringWithFormat:@"%d秒",(int)(timeLast- now)] forState:UIControlStateNormal];
        [self.reCodeBtn setTitle:[NSString stringWithFormat:@"%d秒",(int)(timeLast- now)] forState:UIControlStateDisabled];
        [self performSelector:@selector(makeTime) withObject:nil afterDelay:0.01];
    });
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
    
    [[NSUserDefaults standardUserDefaults] setObject:[NSString stringWithFormat:@"%f",[NSDate date].timeIntervalSince1970 + 120] forKey:REGIST_CODE_TIME];
    [[NSUserDefaults standardUserDefaults] synchronize];
    [self makeTime];
    self.navigationController.navigationBarHidden = NO;
}
- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(makeTime) object:nil];
}
@end
